package com.nongtai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nongtai.constant.JwtClaimsConstant;
import com.nongtai.constant.RedisConstant;
import com.nongtai.exception.UserNotFoundException;
import com.nongtai.mapper.UserMapper;
import com.nongtai.pojo.dto.UserLoginDto;
import com.nongtai.pojo.entity.User;
import com.nongtai.pojo.vo.UserVo;
import com.nongtai.result.Result;
import com.nongtai.service.UserService;
import com.nongtai.utils.JwtUtil;
import com.nongtai.utils.MD5Util;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yza
 * @version 1.0
 * @date 2024/7/11 16:41
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public Result doLogin(UserLoginDto user) {
        // 对前端数据校验
        if(user == null){
            return Result.error("非法用户","-1");
        }
        String account = user.getAccount();
        String password = user.getPassword();
        if(password == null || password.equals("") || account == null || account.equals("")){
            return Result.error("非法用户","-1");
        }

        // 查询用户信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("account",account);
        User userInfo = userMapper.selectOne(userQueryWrapper);
        // 未找到
        if (userInfo == null){
            throw new UserNotFoundException();
        }
        // 校验密码
        String userPasswordMd5 = MD5Util.encryptToMD5(password);
        if(!userPasswordMd5.equals(userInfo.getPassword())){
            return Result.error("密码不正确","400");
        }

        // 生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,userInfo.getId());
        String token = jwtUtil.createJwt(claims);

        // 将用户的token存入redis中保证用户只能在一个客户端登录
        redisTemplate.opsForHash().put(RedisConstant.USER_SESSION,userInfo.getId().toString(),token);

        UserVo userVo = new UserVo();
        userVo.setId(userInfo.getId());
        userVo.setMobile(userInfo.getMobile());
        userVo.setToken(token);
        userVo.setNickname(userInfo.getNickname());
        userVo.setGender(userInfo.getGender());
        userVo.setBirthday(userInfo.getBirthday());

        return Result.success(userVo);
    }
}
